import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login.vue'
import Home from '@/views/Home.vue'
import HomePage from '@/views/HomePage.vue'
import Users from '@/components/user/Users.vue'
import Information from '@/components/medicine/Information.vue'
import In from '@/components/stock/In.vue'
import Out from '@/components/stock/Out.vue'
import SingleChart from '@/components/chart/SingleChart.vue'
import AllChart from '@/components/chart/AllChart.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home ,
    redirect: '/homepage',
    children: [
      { path:'/homepage', component: HomePage },
      { path:'/users', component: Users },
      { path:'/information', component: Information },
      { path:'/in', component: In },
      { path:'/out', component: Out },
      { path:'/singlechart', component: SingleChart },
      { path:'/allchart', component: AllChart }
    ]
  },
]

const router = new VueRouter({
  routes
})

/* 解决路由重复的报错 */
const oPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return oPush.call(this, location).catch(error => error)
}

/* 路由守卫 */
router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    return next()
  }
  const tokenS = window.sessionStorage.getItem('token')
  if (!tokenS) {
    return next('/login')
  }
  next()
})

export default router
